<template>
  <el-card shadow="never">
    <div class="activity-publish-container">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="activity-form">
        <h3>{{ isEdit ? '编辑活动' : '发布活动' }}</h3>
        <el-form-item label="活动标题" prop="activityTitle">
          <el-input v-model="form.activityTitle" placeholder="请输入活动标题" />
        </el-form-item>

        <!-- 富文本编辑器 -->
        <el-form-item label="活动内容" prop="activityContext">
          <!-- <ArtWangEditor class="el-top" ref="refArtWangEditor" v-model="editorHtml" /> -->
          <Tinymce v-model="content" />
        </el-form-item>

        <el-form-item label="活动标签" prop="activityTag">
          <div class="tags-container">
            <el-tag
              v-for="tag in tags"
              :key="tag"
              class="tag-item"
              closable
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="InputRef"
              v-model="inputValue"
              class="tag-input"
              size="small"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button v-else class="button-new-tag" size="small" @click="showInput">
              <el-icon>
                <Plus />
              </el-icon>
              添加标签
            </el-button>
          </div>
        </el-form-item>

        <!-- <el-form-item label="活动分类" prop="menuId">
                  <el-cascader
                      v-model="menuId"
                      :options="options"
                      :props="props"
                      @change="handleChange"
                  />
              </el-form-item> -->

        <el-form-item label="活动摘要" prop="activityDigest">
          <el-input
            v-model="form.activityDigest"
            type="textarea"
            :rows="3"
            placeholder="请输入活动摘要，将显示在活动列表中"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="选择开始时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="选择结束时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动地点" prop="location">
              <div class="flex items-center w-full">
                <div class="flex-1">
                  <el-input v-model="form.location" placeholder="请选择位置" />
                </div>
                <el-button class="ml-2" @click="openMapSelection">
                  <el-icon><Location /></el-icon>
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大人数" prop="maxParticipants">
              <el-input-number v-model="form.maxParticipants" :min="1" :max="1000" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="封面图片" prop="activityShowImg">
          <div class="w-full">
            <MyUpload :file-list="fileList" @deleteFile="deleteFile" @uploadFileSuccess="success" />
          </div>
        </el-form-item>

        <el-col :span="24">
          <el-form-item label="附件图片">
            <div class="w-full">
              <MyUpload
                :file-list="fileInfo"
                @deleteFile="fileInfoDeleteFile"
                @uploadFileSuccess="fileInfoSuccess"
              />
            </div>
          </el-form-item>
        </el-col>

        <div class="pulishInfo">
          <div>
            <h3>发布平台</h3>
            <el-checkbox-group v-model="strategyType">
              <el-checkbox label="官网" :value="1"></el-checkbox>
            </el-checkbox-group>
          </div>
        </div>

        <div class="flex justify-end">
          <el-button type="primary" @click="pulishActivity">发布</el-button>
        </div>
      </el-form>
      <MapSelection
        v-model="mapVisible"
        :center="{
          lng: 114.17842233364557,
          lat: 30.506250728187435
        }"
        ref="mapSelectionRef"
        @confirm="handleMapConfirm"
      />
    </div>
  </el-card>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted, nextTick } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import { useRoute, useRouter } from 'vue-router'
  import { watch } from 'vue'
  import {
    scenicActivitySaveActivityUsingPost,
    scenicActivityGetActivityByIdUsingPost
  } from '@/api/4a/huodongguanli'
  import MapSelection from '@/components/mapSelection/index.vue'
  import Tinymce from '@/components/tinymce/index.vue'

  const router = useRouter()
  const route = useRoute()
  const isEdit = ref(false)
  const activityId = ref<string>(route.query.id ? String(route.query.id) : '')
  const formRef = ref<FormInstance>()
  const inputVisible = ref(false)
  const inputValue = ref('')
  const InputRef = ref()
  const editorHtml = ref('') // 编辑器内容
  let tags = ref<string[]>([]) // 标签
  const menuId = ref([])
  const strategyType = ref([1]) // 默认选中官网
  //   const options = ref([])
  // let id = ref('')
  //   const props = {
  //     expandTrigger: 'hover' as const,
  //     checkStrictly: true
  //   }
  //   let refArtWangEditor = ref<any>('')
  const content = ref('')
  // 初始表单数据
  const iniTForm = reactive<any>({
    fileInfo: '[]', // 附件信息
    id: undefined,
    activityTitle: '', // 活动标题
    activityDigest: '', // 活动摘要
    activityShowImg: '', // 封面图片
    activityContext: '', // 活动内容
    activityTag: '', // 活动标签
    startTime: '', // 开始时间
    endTime: '', // 结束时间
    location: '', // 活动地点
    locationJson: '',
    maxParticipants: 50, // 最大参与人数
    sendDeptNameId: '(0)', // 出品部门ID
    sendTime: '', // 发布时间
    showType: 1, // 展示类型【1信息详情】
    messageStrategyBoList: [
      {
        browseCount: 0,
        id: undefined,
        sendStatus: 2,
        strategyParam: '',
        strategyType: 1,
        websiteMenuMessageBoList: [
          {
            menuId: 1,
            messageId: undefined,
            orderNum: 1,
            websiteId: 1
          }
        ]
      }
    ]
  })

  // 表单数据
  const form = reactive({ ...iniTForm })

  // 将(武汉)(体育) 改成 ["武汉","体育"]
  const processTagsWithBrackets = (tagString: string | undefined): string[] => {
    if (!tagString) return []
    // 匹配括号中的内容
    const regex = /\(([^)]+)\)/g
    const matches = tagString.match(regex)
    if (!matches) return [tagString]
    // 提取括号中的内容
    return matches.map((tag) => tag.slice(1, -1))
  }

  // 将接口的yyyymmddHHMMSS格式转化为yyyy-mm-dd HH:MM:SS
  const formatDateTime = (input: any) => {
    return input.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:$6')
  }

  // 将前端的yyyy-mm-dd HH:MM:SS格式转化为yyyymmddHHMMSS
  function formatToCompactDateTime(input: any) {
    return input.replace(/[^\d]/g, '')
  }

  // 获取活动详情
  const getActivityDetail = async () => {
    if (activityId.value) {
      isEdit.value = true
      try {
        const res = await scenicActivityGetActivityByIdUsingPost({
          params: {
            activityId: activityId.value as any
          }
        })
        if (res.code === 0) {
          const newData = { ...res.data }
          Object.assign(form, newData)
          form.activityTitle = newData.activityName
          // refArtWangEditor.value.setHtml(newData.introduction)
          content.value = newData.introduction || ''
          tags.value = newData.featureTag ? processTagsWithBrackets(res.data?.featureTag) : []
          form.activityDigest = newData.description
          form.startTime = formatDateTime(newData.startTime)
          form.endTime = formatDateTime(newData.endTime)

          // 绑定菜单id
          menuId.value = form.messageStrategyBoList[0].websiteMenuMessageBoList[0].menuId
          strategyType.value = form.messageStrategyBoList[0].strategyType
            ? [form.messageStrategyBoList[0].strategyType]
            : [1]

          // 安全地处理文件列表数据
          try {
            form.activityShowImg = res.data?.imageUrl || '[]'
            if (typeof form.activityShowImg === 'string') {
              const parsed = JSON.parse(form.activityShowImg)
              if (!Array.isArray(parsed)) {
                form.activityShowImg = '[]'
              }
            }
          } catch (e) {
            console.warn('文件列表数据格式错误:', e)
            form.activityShowImg = '[]'
          }

          editorHtml.value = form.activityContext || ''
        }
      } catch (error) {
        console.error('获取活动详情失败', error)
        ElMessage.error('获取活动详情失败')
      }
    }
  }

  // 活动地点打开地图选择
  const openMapSelection = () => {
    mapVisible.value = true
    mapSelectionRef.value.openPopup({
      lng: form.locationJson.longitude,
      lat: form.locationJson.latitude
    })
  }
  const mapVisible = ref(false)
  const mapSelectionRef = ref()

  const handleMapConfirm = (data: any) => {
    // 更新位置信息
    if (data && data.point && data.surroundingPois.length > 0) {
      form.location = data.surroundingPois[0].title // 保存坐标值

      // 更新locationJson，存储完整的位置数据，兼容各个端口的字段
      form.locationJson = {
        longitude: data.point.lng, //经度
        latitude: data.point.lat, //纬度
        height: data.point.height || 0
      }
      formRef.value?.validateField('location')
      mapVisible.value = false
    } else {
      ElMessage.error('请选择位置')
    }
  }

  // 封面图片
  const fileList = computed({
    get() {
      try {
        return JSON.parse(form.activityShowImg || '[]')
      } catch {
        return []
      }
    },
    set(val) {
      form.activityShowImg = JSON.stringify(val)
    }
  })

  // 附件图片
  const fileInfo = computed({
    get() {
      try {
        return JSON.parse(form.fileInfo)
      } catch {
        return []
      }
    },
    set(val) {
      form.fileInfo = JSON.stringify(val)
    }
  })

  // 删除封面图片
  const deleteFile = (params: any) => {
    fileList.value = fileList.value.filter((item: any) => item.path !== params.path)
    formRef.value?.validateField('activityShowImg')
  }

  // 删除附件
  const fileInfoDeleteFile = (params: any) => {
    fileInfo.value = fileInfo.value.filter((item: any) => item.path !== params.path)
  }

  // 上传封面图片成功
  const success = (response: any) => {
    fileList.value = [...fileList.value, response.data]
    formRef.value?.validateField('activityShowImg')
  }

  // 上传附件成功
  const fileInfoSuccess = (response: any) => {
    fileInfo.value = [...fileInfo.value, response.data]
  }

  // 获取分类列表
  const getMenuList = async () => {
    // 实际API调用应该类似于下面的代码
    // try {
    //   const res = await scenicWebsiteQueryWebsiteMenuInfoUsingGet({})
    //   if (res.code === 0) {
    //     const list = res.data
    //     options.value = []
    //     list.forEach((item) => {
    //       let children = []
    //       if (item.children?.length > 0) {
    //         children = item.children.map((child) => {
    //           return {
    //             value: child.id,
    //             label: child.menuName
    //           }
    //         })
    //       }
    //       options.value.push({
    //         value: item.id,
    //         label: item.menuName,
    //         children: children.length > 0 ? children : null
    //       })
    //     })
    //   }
    // } catch (error) {
    //   console.error('获取分类失败', error)
    //   ElMessage.error('获取分类失败')
    // }
  }

  // 分类选择事件
  //   const handleChange = (value: any) => {
  //     console.log(value)
  //   }

  const validatePass = (rule: any, value: any, callback: any) => {
    if (value && form.locationJson) {
      callback()
    } else {
      callback(new Error('请选择活动地点'))
    }
  }
  // 表单验证规则
  const rules = reactive<FormRules>({
    activityTitle: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
    activityContext: [{ required: true, message: '请输入活动内容', trigger: 'blur' }],
    activityDigest: [{ required: true, message: '请输入活动摘要', trigger: 'blur' }],
    startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
    location: [{ required: true, validator: validatePass, trigger: 'blur' }],
    maxParticipants: [{ required: true, message: '请输入最大参与人数', trigger: 'blur' }],
    activityShowImg: [{ required: true, message: '请上传封面图片', trigger: 'change' }]
  })

  // 显示标签输入框
  const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
      InputRef.value?.input?.focus()
    })
  }

  // 标签输入确认
  const handleInputConfirm = () => {
    if (inputValue.value) {
      tags.value.push(inputValue.value)
      // 组合标签格式(tag1)(tag2)
      form.activityTag = tags.value.map((tag) => `(${tag})`).join('')
    }
    inputVisible.value = false
    inputValue.value = ''
  }

  // 删除标签
  const handleClose = (tag: string) => {
    tags.value.splice(tags.value.indexOf(tag), 1)
    // 组合标签格式(tag1)(tag2)
    form.activityTag = tags.value.map((tag) => `(${tag})`).join('')
  }

  // 生成活动对象
  const generateActivityObject = () => {
    // 更新表单内容
    // form.activityContext = refArtWangEditor.value.getHtml().replace(/<[^>]*>/g, '') // 获取富文本的值，移除所有HTML标签
    form.activityContext = content.value
    const activityData = {
      activityName: form.activityTitle,
      introduction: form.activityContext,
      featureTag: form.activityTag,
      locationJson: JSON.stringify(form.location),
      location: form.location,
      description: form.activityDigest,
      startTime: formatToCompactDateTime(form.startTime),
      endTime: formatToCompactDateTime(form.endTime),
      imageUrl: form.activityShowImg,
      galleryImages: form.fileInfo,
      registration: 1,
      apply: 1,
      strategyType: form.messageStrategyBoList[0].strategyType,
      websiteMenuActivityBoList: [
        {
          websiteId: 1,
          menuId: 1
        }
      ],
      START_TIME: new Date().getTime() + '0'
    }

    // 更新菜单ID
    //   if (menuId.value) {
    //     activityData.messageStrategyBoList[0].websiteMenuMessageBoList[0].menuId = menuId.value
    //   }

    // 更新平台
    //   activityData.messageStrategyBoList[0].strategyType = strategyType.value?.[0] || 1

    return activityData
  }

  // 发布活动
  const pulishActivity = async () => {
    const activityData = generateActivityObject()
    if (!formRef.value) return
    await formRef.value.validate(async (valid, fields) => {
      if (valid) {
        // 实际API调用应该类似于下面的代码
        try {
          let res
          if (isEdit.value) {
            // 编辑活动
            res = await scenicActivitySaveActivityUsingPost({
              body: activityData
            })
          } else {
            // 新增活动
            res = await scenicActivitySaveActivityUsingPost({
              body: activityData
            })
          }
          if (res.code === 0) {
            ElMessage.success(isEdit.value ? '活动更新成功' : '活动发布成功')
            router.push({ path: '/activity/list' })
          } else {
            ElMessage.error(res.msg || '操作失败')
          }
        } catch (error) {
          console.error('发布活动失败', error)
          ElMessage.error('发布活动失败')
        }
      } else {
        console.log('表单校验失败', fields)
      }
    })
  }

  // 监听编辑器内容变化
  watch(editorHtml, (newVal) => {
    form.activityContext = newVal
  })

  // 监听路由ID变化
  watch(
    () => route.query.id,
    (newValue) => {
      if (newValue) {
        activityId.value = String(newValue) // 确保ID始终是字符串类型
        if(route.path === '/activity/activity-publish'){
          getActivityDetail()
        }
      } else {
        activityId.value = ''
        Object.assign(form, iniTForm) // 重置表单
        editorHtml.value = ''
        tags.value = []
      }
    }
  )

  onMounted(() => {
    getMenuList()
    if (activityId.value) {
      getActivityDetail()
    }
  })

  // Cleanup function
  // onBeforeUnmount(() => {
  //     // Clear any timers, event listeners or other resources
  //     if (refArtWangEditor.value) {
  //         refArtWangEditor.value.destroy()
  //     }
  // })
</script>

<style lang="scss" scoped>
  // .activity-publish-container {
  //     width: 100%;
  //     height: 100%;
  // }

  .activity-form {
    // padding: 20px;
    // background-color: #fff;
    // border-radius: 8px;
    // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 5%);

    h3 {
      margin-bottom: 20px;
      font-size: 20px;
      font-weight: 500;
    }
  }

  .tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;

    .tag-item {
      margin-right: 0;
    }

    .tag-input {
      width: 100px;
      margin-right: 8px;
      vertical-align: bottom;
    }
  }

  .pulishInfo {
    display: flex;
    justify-content: space-between;
    padding: 20px;
    margin: 20px 0;
    // background-color: #f5f7fa;
    border-radius: 4px;

    h3 {
      margin-bottom: 15px;
      font-size: 16px;
      font-weight: 500;
    }

    .el-checkbox {
      margin-right: 20px;
    }
  }

  .el-top {
    margin-top: 10px;
  }

  .el-date-picker {
    width: 100%;
  }

  .activity-category {
    margin-right: 15px;
  }
 .el-card{
    border-radius: 8px !important;
    margin-bottom: 20px !important;
  }
</style>
